<?php
class api extends base{

	public function init(){ // 公用
		parent::init(); // 这是必须的

		$this->upload_groupObj = D('upload_group');
		$this->upload_fileObj = D('upload_file');

		// 存储引擎
		$this->config = $this->setting['storage'];
		$this->storage = $this->config['default'];

		$this->getUser();
		
	}

	public function upload_image()
    {	
		$group_id = arg('group_id');
		$fileInfo = $_FILES['file'];
		// dump($fileInfo);exit;
		$result = $this->upload_fileObj->upload_image($this->config,$fileInfo);
		// dump($result);exit;
		if($result){
			$fileDir = $result['fileDir'];
			$fileName = $result['fileName'];
			// 添加文件库记录
			$uploadFile = $this->addUploadFile($group_id, $fileDir, $fileName, $fileInfo, 'image');
			$data['name'] = $uploadFile['file_id'];
			$data['url'] = $uploadFile['file_url'].$uploadFile['file_name'];

			// $data = $uploadFile['file_url'].$uploadFile['file_name'];
			$arr = array('status'=>'ok', 'data' => $data, 'result' => '图片上传成功');
			exit(json_encode($arr));
		}else{
			$arr = array('status'=>'error', 'data' => '' , 'result' => '图片上传失败');
			exit(json_encode($arr));
		}
    }

	private function addUploadFile($group_id, $fileDir, $fileName, $fileInfo, $fileType)
    {

		$storage = $this->config['default'];
		// 存储域名
		$fileUrl = isset($this->config['engine'][$storage]['domain'])
			? $this->config['engine'][$storage]['domain'].$fileDir.'/' : $fileDir.'/';
		// 添加文件库记录
		$data = [
			// 'site_id' => $this->site['id'],
			// 'company_id' => $this->company['id'],
			'user_id' => $this->admin['id'],
            'group_id' => $group_id > 0 ? (int)$group_id : 0,
            'storage' => $storage,
            'file_url' => $fileUrl,
            'file_name' => $fileName,
            'file_size' => $fileInfo['size'],
            'file_type' => $fileType,
			'extension' => pathinfo($fileInfo['name'], PATHINFO_EXTENSION),
			// 'is_user' => 1,
		];
		$data['file_id'] = $this->upload_fileObj->add($data);
        return $data;
    }

	function remove() {
		$file = arg('file');
		// $photo = D('Photo')->where(array('photo' => $file))->find();
		// if($photo['uid'] == $this->uid){
			@unlink('./upload/'.$file); 
			// D('Photo')->delete($photo['id']);
		// }
	}

    //ajaxdata
	function ajaxtel(){
		header('Content-Type:application/json; charset=utf-8');
		$tel = arg('tel');
		$res = D('company_user')->find(array("status=1 and tel='{$tel}' and ".$this->cond));
		if($res){
			$data['code'] = 1;
			$data['tel'] = $res['tel'];
			$data['realname'] = $res['realname'];
			$data['company'] = $res['company'];
			$data['username'] = $res['username'];
			exit(json_encode($data));
		}else{
			$this->ajaxMsg('手机号不存在');
		}
	}
	
}